package avicit.bdp.dds.api.dto.resources.filter;

import avicit.bdp.dds.dao.entity.Resource;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * resource filter
 */
public class ResourceFilter implements IFilter {
    /**
     * resource suffix
     */
    private String suffix;
    /**
     * resource list
     */
    private List<Resource> resourceList;

    /**
     * parent list
     */
    //Set<Resource> parentList =  new HashSet<>();

    /**
     * constructor
     * @param suffix        resource suffix
     * @param resourceList  resource list
     */
    public ResourceFilter(String suffix, List<Resource> resourceList) {
        this.suffix = suffix;
        this.resourceList = resourceList;
    }

    /**
     * file filter
     * @return file filtered by suffix
     */
    public Set<Resource> fileFilter(){
        Set<Resource> resources = resourceList.stream().filter(t -> {
            String alias = t.getName();
            return alias.endsWith(suffix);
        }).collect(Collectors.toSet());
        return resources;
    }

    /**
     * list all parent dir
     * @return parent resource dir set
     */
    Set<Resource> listAllParent(){
        Set<Resource> parentList =  new HashSet<>();
        Set<Resource> filterFileList = fileFilter();
        for(Resource file:filterFileList){
            parentList.add(file);
            setAllParent(file,parentList);
        }
        return parentList;

    }

    /**
     * list all parent dir
     * @param resource  resource
     * @return parent resource dir set
     */
    private void setAllParent(Resource resource,Set<Resource> parentList){
        for (Resource resourceTemp : resourceList) {
            if (resourceTemp.getId() == resource.getPid()) {
                parentList.add(resourceTemp);
                setAllParent(resourceTemp,parentList);
            }
        }
    }

    @Override
    public List<Resource> filter() {
        return new ArrayList<>(listAllParent());
    }
}
